package com.gitee.tje.waving.aop;


import com.gitee.tje.waving.beans.BeanFactoryProcessor;
import com.gitee.tje.waving.beans.BeanProcessor;
import com.gitee.tje.waving.factory.BeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * scanner
 *
 * @author taojiaen
 * @date 2018-03-18 19:50
 */
public class AopWavingScanner implements BeanFactoryProcessor, BeanProcessor {
    private AopCreator aopCreator;
    private BeanFactory beanFactory;

    @Override
    public void processBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
        creteAopCreateor();
    }

    @Override
    public Object processAfterInitiation(String beanName, Class<?> beanClazz, Object bean) {
        if (beanClazz.isAssignableFrom(Advisor.class)) {
            return bean;
        }

        return aopCreator.create(bean);
    }

    private void creteAopCreateor() {
        if (aopCreator != null) {
            return;
        }
        synchronized (this) {
            if (aopCreator == null) {
                List<Advisor> advisorList = new ArrayList<>();
                for (String beanName : beanFactory.getBeanName(Advisor.class)) {
                    advisorList.add((Advisor) beanFactory.getBean(beanName));
                }
                this.aopCreator = new AopCreator(advisorList);
            }
        }
    }

}
